package com.whq.service.weixin.impl;

import com.alibaba.fastjson.JSON;
import com.whq.entity.Member;
import com.whq.service.MemberService;
import com.whq.service.weixin.EventsService;
import com.whq.websocket.SystemWebSocketHandler;
import com.whq.weixin.entity.WeChatReceiveMsg;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.socket.TextMessage;

import java.util.List;

/**
 * Created by 海易出行 on 2016/9/20.
 */
@Service
public class ScanEventsServiceImpl implements EventsService {

    @Autowired
    MemberService memberService;



    @Autowired
    SubscribeEventsServiceImpl subscribeEventsService;


    @Override
    public String response(WeChatReceiveMsg msg) throws Exception {
        String eventKey = msg.getEventKey();
        System.out.println(JSON.toJSONString(msg));
        String message = null;
        if (StringUtils.isNotBlank(eventKey)) {
            SystemWebSocketHandler systemWebSocketHandler = new SystemWebSocketHandler();
            Long id = null;
            if (eventKey.startsWith("toBackstageLogin")) {// 登陆
                Member member = new Member();
                member.setOpenid(msg.getFromUserName());
                List<Member> members = memberService.selectByCondition(member);
                if(CollectionUtils.isEmpty(members)){
                    systemWebSocketHandler.sendMessageToUser("123456",new TextMessage("websocket_用户未注册"));
                    return "ok";
                }
                member = members.get(0);
                //
                if(member.getSysuserId().toString().equals("111")){
                    systemWebSocketHandler.sendMessageToUser("123456",new TextMessage("websocket_登陆成功"));
                }else {
                    systemWebSocketHandler.sendMessageToUser("123456",new TextMessage("websocket_您没有权限"));
                }
            }
        }

        return subscribeEventsService.focusOnPush(msg,message);
    }
}
